from PyQt5.QtWidgets import (
    QListWidgetItem,
    QVBoxLayout,
    QDialog,
    QListWidget
)
from PyQt5.QtCore import Qt
from .recorder_dialog import RecorderDialog
from .recorder import Recorder
from os import listdir, path, makedirs
from .utils import relative


class LogDialog(QDialog):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle("Log System")
        self.log_dir = relative("logs")
        if not path.isdir(self.log_dir):
            makedirs(self.log_dir)

        list_widget = QListWidget(self)
        logs = sorted(listdir(self.log_dir), reverse=True)

        for name in logs:
            list_widget.addItem(QListWidgetItem(name))
        list_widget.itemDoubleClicked.connect(self.preview)
        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(list_widget)

        self.setLayout(self.v_layout)

        # 设置对话框类型
        self.setWindowFlags(Qt.Tool)

    def preview(self, item):
        recorder = Recorder()
        recorder.load(path.join(self.log_dir, item.text()))
        dialog = RecorderDialog(recorder)
        if dialog.exec_() == QDialog.Accepted:
            pass
